package com.mc.algorithm;

import java.util.Scanner;
import java.util.Arrays;
import java.util.Stack;


/**
 * 火车进出站问题
 * @author MC
 *
 */
public class Train{
	private static int[] seq;
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            int[] input = new int[n];
            int[] output = new int[n];
            seq = new int[n];
            boolean[] flag = new boolean[n]; 
            for(int i=0;i<n;i++){
            	seq[i] = sc.nextInt();
            	input[i] = seq[i];
            }
            
            Arrays.sort(input);
            recurse(0,n,input,output,flag);
        }
    }
    public static void recurse(int loc,int n,int[] input,int[] output,boolean[] flag){
        if(loc==n){
			if(!isStack(output))
				return;
        	
			for(int i=0;i<n;i++)
                System.out.print(output[i]+" ");
            System.out.println();
            return;
        }
        for(int i=0;i<n;i++){
            if(!flag[i]){
                flag[i]=true;
                output[loc]=input[i];
                recurse(loc+1,n,input,output,flag);
            	flag[i]=false;
            }
        }
    }
    
    public static boolean isStack(int[] output){
    	Stack<Integer> stack = new Stack<Integer>();
    	int i=0;
    	int j=0;
    	int n = seq.length;
    	while(i<n){
    		stack.push(seq[i++]);
    		while(j<n&&!stack.isEmpty()&&stack.peek()==output[j]){
    			stack.pop();
    			j++;
    		}
    		if(j==n)
    			return true;
    	}
    	return false;
    }
}